package com.framework.collection.List;

import java.util.Iterator;
import java.util.NoSuchElementException;

/**
 * @author duanzhizhou
 * @date 2025/4/21
 */
public class ArrayList<E> implements List<E>{
    
    private Object[] arr = new Object[10];
    
    private int size;
    
    @Override
    public int size() {
        return size;
    }
    
    @Override
    public boolean isEmpty() {
        return size == 0;
    }
    
    @Override
    public void add(E e) {
        if (size == arr.length) {
            resize();
        }
        arr[size++] = e;
    }
    
    private void resize() {
        Object[] newArr = new Object[arr.length * 2];
        System.arraycopy(arr, 0, newArr, 0, arr.length);
        this.arr = newArr;
    }
    
    @Override
    public E get(int index) {
        if (index < 0 || index >= size) {
            throw new IndexOutOfBoundsException();
        }
        return (E) arr[index];
    }
    
    @Override
    public E set(int index, E e) {
        if (index < 0 || index >= size) {
            throw new IndexOutOfBoundsException();
        }
        E oldVal = (E) arr[index];
        arr[index] = e;
        return oldVal;
    }
    
    @Override
    public E remove(int index) {
        if (index < 0 || index >= size) {
            throw new IndexOutOfBoundsException();
        }
        E old = (E) arr[index];
        System.arraycopy(arr, index + 1, arr, index, size - index - 1);
        arr[size--] = null;
        return old;
    }
    
    @Override
    public void add(int index, E e) {
        if (size == arr.length) {
            resize();
        }
        System.arraycopy(arr, index, arr, index + 1, size - index);
        arr[index] = e;
    }
    
    
    @Override
    public Iterator<E> iterator() {
        return new ArrItr();
    }
    
    class ArrItr implements Iterator<E> {
        private int cursor;
        @Override
        public boolean hasNext() {
            return cursor < size;
        }
        
        @Override
        public E next() {
            if (cursor >= size) {
                throw new NoSuchElementException();
            }
            return (E) arr[cursor++];
        }
    }
}
